package com.mashrabenaab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import com.mashrabenaab.adapter.MnAdapterLocal;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class LocalListActivity extends ListActivity {
	private ArrayList<Magazine> arrMagazine;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mn_list_local);
		if (arrMagazine == null) {
			//loadData();
		}
	}

	private void loadData() {
		try {
			arrMagazine = new ArrayList<Magazine>();
			URL url = new URL(getString(R.string.url_base) + "info.txt");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String strLine;
			while ((strLine = in.readLine()) != null) {
				Magazine magazine = new Magazine();
				String[] strArr = splitString(strLine, "-");
				magazine.setEdition(strArr[0]);
				magazine.setMonthName(GlobalService.getMonthName(strArr[1]));
				magazine.setYearName(strArr[2]);
				magazine.setPagecount(strArr[3]);

				String imageUrl = GlobalService.getFolderNameLive(magazine,
						this) + "thumb.gif";
				magazine.setImageUrl(imageUrl);
				arrMagazine.add(magazine);
				MnAdapterLocal m_adapter = new MnAdapterLocal(
						LocalListActivity.this, arrMagazine);
				setListAdapter(m_adapter);
			}
			in.close();
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException is : ", e.toString());
		} catch (IOException e) {
			Log.e("IOException is : ", e.toString());
		}
	}

	public static String[] splitString(String original, String separator) {
		Vector nodes = new Vector();
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		nodes.addElement(original);
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++) {
				result[loop] = (String) nodes.elementAt(loop);
			}
		}
		return result;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Magazine cc = (Magazine) l.getItemAtPosition(position);

		Context context = getApplicationContext();
		CharSequence text = "Edition is : " + cc.getEdition();
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
}